package com.bookocean.domain.service;

import com.bookocean.controller.dto.CloudHanPostDto;
import com.bookocean.controller.dto.CommentDto;
import com.bookocean.controller.dto.PageResultDto;
import com.bookocean.domain.repository.BookQuoteRepository;
import com.bookocean.domain.repository.BookRepository;
import com.bookocean.domain.repository.UserRepository;
import com.bookocean.domain.repository.BookLikeRepository;
import com.bookocean.domain.repository.BookFavoriteRepository;
import com.bookocean.domain.repository.BookCommentRepository;
import com.bookocean.domain.utils.UserContextHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;
import java.util.ArrayList;

/**
 * 云汉页面领域服务
 * 
 * @author BookOcean
 * @since 2024-01-01
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class CloudHanDomainService {

    private final BookQuoteRepository bookQuoteRepository;
    private final BookLikeRepository bookLikeRepository;
    private final BookFavoriteRepository bookFavoriteRepository;
    private final BookCommentRepository bookCommentRepository;

    /**
     * 获取云汉页面热门书摘（点赞+评论排序）
     * 
     * @param page 页码
     * @param pageSize 每页数量
     * @param categoryId 分类ID（可选）
     * @return 分页热门书摘列表
     */
    public PageResultDto<CloudHanPostDto> getHotPosts(Integer page, Integer pageSize, Integer categoryId) {
        // 获取书摘列表
        List<CloudHanPostDto> posts = bookQuoteRepository.getHotPosts(page, pageSize, categoryId);
        
        // 获取总数
        Long total = bookQuoteRepository.getHotPostsCount(categoryId);
        
        // 填充完整信息
        posts = fillPostDetails(posts);
        
        // 按热门分数排序
        posts.sort((a, b) -> {
            double scoreA = calculateHotScore(a);
            double scoreB = calculateHotScore(b);
            return Double.compare(scoreB, scoreA);
        });
        
        return PageResultDto.of(posts, total, page, pageSize);
    }

    /**
     * 获取云汉页面最新书摘
     * 
     * @param page 页码
     * @param pageSize 每页数量
     * @param categoryId 分类ID（可选）
     * @return 分页最新书摘列表
     */
    public PageResultDto<CloudHanPostDto> getLatestPosts(Integer page, Integer pageSize, Integer categoryId) {
        // 获取书摘列表
        List<CloudHanPostDto> posts = bookQuoteRepository.getLatestPosts(page, pageSize, categoryId);
        
        // 获取总数
        Long total = bookQuoteRepository.getLatestPostsCount(categoryId);

        // 填充完整信息
        posts = fillPostDetails(posts);
        
        // 如果没有数据，返回提示信息
        if (posts.isEmpty() && total == 0) {
            log.info("最新书摘列表为空，分类ID: {}", categoryId);
        }
        
        return PageResultDto.of(posts, total, page, pageSize);
    }

    /**
     * 搜索云汉页面书摘（书名/作者/内容模糊匹配）
     * 
     * @param keyword 搜索关键词
     * @param page 页码
     * @param pageSize 每页数量
     * @param categoryId 分类ID（可选）
     * @return 分页搜索结果
     */
    public PageResultDto<CloudHanPostDto> searchCloudHanPosts(
            String keyword, Integer page, Integer pageSize, Integer categoryId) {
        
        // 搜索书摘
        List<CloudHanPostDto> posts = bookQuoteRepository.searchPosts(keyword, page, pageSize, categoryId);
        
        // 获取总数
        Long total = bookQuoteRepository.searchPostsCount(keyword, categoryId);
        
        // 填充完整信息
        posts = fillPostDetails(posts);
        
        return PageResultDto.of(posts, total, page, pageSize);
    }

    /**
     * 填充书摘详细信息
     * 
     * @param posts 书摘列表
     * @return 填充后的书摘列表
     */
    private List<CloudHanPostDto> fillPostDetails(List<CloudHanPostDto> posts) {
        Long currentUserId = getCurrentUserId();
        
        return posts.stream().map(post -> {
            // 填充书籍信息
            if (post.getBook() == null) {
                post.setBook(new CloudHanPostDto.BookInfo());
            }
            
            // 填充用户信息
            if (post.getUser() == null) {
                post.setUser(new CloudHanPostDto.UserInfo());
            }
            
            // 获取点赞、评论、收藏数量
            post.setLikeCount(bookLikeRepository.getLikeCount(post.getId()));
            post.setCommentCount(bookCommentRepository.getCommentCount(post.getId()));
            post.setFavoriteCount(bookFavoriteRepository.getFavoriteCount(post.getId()));
            
            // 检查当前用户是否点赞、收藏
            post.setIsLiked(bookLikeRepository.existsByQuoteIdAndUserId(post.getId(), currentUserId));
            post.setIsFavorited(bookFavoriteRepository.existsByQuoteIdAndUserId(post.getId(), currentUserId));
            
            // 获取评论预览
            post.setComments(bookCommentRepository.getCommentPreview(post.getId(), 2));
            
            return post;
        }).collect(Collectors.toList());
    }

    /**
     * 计算热门分数
     * 
     * @param post 书摘
     * @return 热门分数
     */
    private double calculateHotScore(CloudHanPostDto post) {
        // 基础分数：点赞×2 + 评论×3 + 收藏×2
        double baseScore = (post.getLikeCount() != null ? post.getLikeCount() : 0) * 2.0 +
                          (post.getCommentCount() != null ? post.getCommentCount() : 0) * 3.0 +
                          (post.getFavoriteCount() != null ? post.getFavoriteCount() : 0) * 2.0;
        
        // 时间衰减：防止老内容一直霸榜
        if (post.getCreatedAt() != null) {
            long daysDiff = java.time.Duration.between(post.getCreatedAt(), java.time.LocalDateTime.now()).toDays();
            double timeDecay = 1.0 + daysDiff / 7.0;
            return baseScore / timeDecay;
        }
        
        return baseScore;
    }

    /**
     * 获取当前用户ID
     * 从用户上下文中获取当前登录用户的ID
     * 
     * @return 当前用户ID
     * @throws RuntimeException 如果用户未登录
     */
    private Long getCurrentUserId() {
        Long userId = UserContextHolder.getUserId();
        if (userId == null) {
            log.warn("尝试获取用户ID但用户未登录");
            // 对于未登录用户，返回一个默认值或抛出异常
            // 这里返回null，让调用方处理
            return null;
        }
        return userId;
    }
}
